using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CollabApp.Domain.Services.Rankings;

namespace CollabApp.API.Controllers;

[ApiController]
[Route("api/rankings")]
public class RankingController : ControllerBase
{
    private readonly IRankingService _rankingService;
    public RankingController(IRankingService rankingService)
    {
        _rankingService = rankingService;
    }

    public class SubmitScoreRequest
    {
        public Guid UserId { get; set; }
        public string Username { get; set; } = string.Empty;
        public string? AvatarUrl { get; set; }
        public int DeltaScore { get; set; }
    }

    [HttpGet("overall")]
    public async Task<IActionResult> GetOverallRanking([FromQuery] int page = 1, [FromQuery] int limit = 20)
        => Ok(await _rankingService.GetOverallRankingAsync(page, limit));

    [HttpPost("overall/submit")]
    public async Task<IActionResult> SubmitOverallScore([FromBody] SubmitScoreRequest request)
    {
        if (request == null || request.UserId == Guid.Empty)
            return BadRequest("invalid request");
        var (score, rank) = await _rankingService.SubmitScoreAsync(request.UserId, request.Username, request.AvatarUrl, request.DeltaScore);
        return Ok(new { message = "score submitted", score, rank });
    }

    [HttpPost("overall/sync")]
    public async Task<IActionResult> SyncOverall()
    {
        await _rankingService.SyncOverallRankingToPgsqlAsync();
        return Ok(new { message = "sync queued" });
    }
}
